﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Goods;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Components.PrintTask;
using NewRetail.Application.Components.PrintTask.Model;
using NewRetail.Application.Components.Warehouse;
using NewRetail.Application.Core;
using NewRetail.Application.Core.Entity;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("goods-adjust-price")]
    public class GoodsAdjustPriceController : BaseController<GoodsAdjustPrice, AdjustPricePagingDto>
    {
        private readonly IWarehouseGoodsService warehouseGoodsService;
        private readonly IAdjustPriceService adjustPriceService;
        private readonly IPrintTaskService printTaskService;

        public GoodsAdjustPriceController(
            IWarehouseGoodsService warehouseGoodsService,
            IAdjustPriceService adjustPriceService,
            IPrintTaskService printTaskService)
        {
            this.warehouseGoodsService = warehouseGoodsService;
            this.adjustPriceService = adjustPriceService;
            this.printTaskService = printTaskService;
        }

        protected override async Task<IQueryable<GoodsAdjustPrice>> FilterQueryPaging(DbContext db, IQueryable<GoodsAdjustPrice> query, AdjustPricePagingDto dto)
        {
            if (!string.IsNullOrWhiteSpace(dto.receiptNo))
            {
                query = query.Where(x => x.receiptNo == dto.receiptNo || x.receiptNo.Contains(dto.receiptNo));
            }

            if (!string.IsNullOrWhiteSpace(dto.warehouseId))
            {
                query = query.Where(x => x.warehouseID == dto.warehouseId);
            }

            await Task.CompletedTask;
            return query;
        }

        public override async Task<ResponseEntity<PagedResultDto<GoodsAdjustPrice>>> QueryPaging([FromBody] AdjustPricePagingDto dto)
        {
            var data = await base.QueryPaging(dto);

            if (data.Data?.Items?.Any() ?? false)
            {
                data.Data.Items = await this.adjustPriceService.AttachGoods(data.Data.Items.ToArray());
                data.Data.Items = await this.adjustPriceService.AttachWarehouse(data.Data.Items.ToArray());
            }

            return data;
        }

        [HttpPost("save-multiple")]
        public async Task<ResponseEntity<GoodsAdjustPrice[]>> SaveMultiple([FromBody] ReceiptNoItemsDto<GoodsAdjustPrice> data)
        {
            var res = await this.Repo.SaveReceiptItems(this.HttpContext.RequestServices, data, "TJ");
            return new ResponseEntity<GoodsAdjustPrice[]>().SetData(res.Items);
        }

        [HttpPost("query-by-receipt-no")]
        public async Task<ResponseEntity<GoodsAdjustPrice[]>> QueryByReceiptNo([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).ToArrayAsync();

            if (data.Any())
            {
                data = await this.adjustPriceService.AttachGoods(data);
                data = await this.adjustPriceService.AttachWarehouse(data);
            }

            return new ResponseEntity<GoodsAdjustPrice[]>().SetData(data);
        }
        /// <summary>
        /// 将调价单添加到打印任务里面
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("save-print-task")]
        public async Task<ResponseEntity<string>> SavePrintTask([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).FirstOrDefaultAsync();
            var printTaskSaveData = new PrintTaskSaveInputDto
            {
                receiptDate = data.receiptDate,
                receiptNo = data.receiptNo,
                printTag = 0,
                printNo = "P0"
            };


            var ret = new ResponseEntity<string>();
            try
            {
                var result = await this.printTaskService.SavePrintTaskItems(printTaskSaveData);
                if (result.Item1 == 0)
                    ret.SetError("创建打印任务失败！" + result.Item2);
                ret.SetData("创建打印任务成功");
            }
            catch (Exception e)
            {
                ret.SetError("创建失败！" + e.Message);
            }

            return ret;
        }
    }
}
